#include "pccoremodel.h"

#include "ImageProcessor.h"
#include "imageprovider.h"


void PCcoreModel::displayImage(int index)
{
    if (index < 0 || index >= m_items.size())
        return;

    const Item &item = m_items[index];
    if (!item.mat.empty()) {
        ImageProcessor::getInstance().setcaptureImgMode(ImageProcessor::CapPause);
        ImageProvider::getInstance().image2qml(item.mat, "Main");
    }
}

void PCcoreModel::clearItems() {
    beginResetModel();
    m_items.clear();
    endResetModel();
}
void PCcoreModel::removeItem(int index) {
    if (index < 0 || index >= m_items.size()) {
        qDebug() << "Invalid index:" << index;
        return;
    }

    bool isSetFalse = m_items[index].isTrain;
    beginRemoveRows(QModelIndex(), index, index);
    m_items.removeAt(index);
    endRemoveRows();

    int newId = 0;

    for (auto &item : m_items) {
        item.id = newId++;
        if(isSetFalse)
            item.isTrain = false;
    }

    emit dataChanged(createIndex(0, 0), createIndex(m_items.size() - 1, 0)); // 通知视图更新
}

PCcoreModel::PCcoreModel(QObject *parent) : QAbstractListModel(parent) {}

void PCcoreModel::addItem(const Item &item) {
    beginInsertRows(QModelIndex(), m_items.size(), m_items.size());
    m_items.append(item);
    endInsertRows();
}

void PCcoreModel::addItem(void *result, const cv::Mat &mat )
{
    std::vector<int8_t> data;
    if (result != nullptr) {
        // 假设 result 是一个指向有效数据的指针，读取数据到 std::vector
        size_t size =  784 * 1536;
        data.assign(static_cast<int8_t*>(result), static_cast<int8_t*>(result) + size);
    }

    Item newItem;
    newItem.mat = mat.clone();
    newItem.isTrain = false;
    newItem.data = data;
    newItem.id = m_items.size();

    addItem(newItem);

}


int PCcoreModel::countUntrainedItems() {
    int count = 0;
    for (const auto &item : m_items) {
        if (!item.isTrain) {
            ++count;
        }
    }
    return count;
}

void PCcoreModel::emitDataCollectionComplete()
{
    emit dataCollectionComplete(countUntrainedItems());
}

void PCcoreModel::resetModel()
{
    beginResetModel();
    endResetModel();
}

void PCcoreModel::finishexportEmbedding() {
    int count = 0; // 记录增加的`数据数量
    for (auto &item : m_items) {
        if (!item.isTrain) {
            item.isTrain = true;
            ++count;
        }
    }
    emit dataChanged(createIndex(0, 0), createIndex(m_items.size() - 1, 0)); // 通知视图更新
    qDebug() << "已完成标记" << count << "个数据为已训练";
}

int PCcoreModel::exportEmbedding(QVector<int8_t> &embedding) {
    embedding.clear();
    int count = 0; // 记录增加的数据数量
    for (auto &item : m_items) {
        if (!item.isTrain) {
            embedding.append(QVector<int8_t>::fromStdVector(item.data));
            ++count;
        }
    }
    return count;
}

int PCcoreModel::rowCount(const QModelIndex &parent) const {
    Q_UNUSED(parent);
    return m_items.size();
}

QVariant PCcoreModel::data(const QModelIndex &index, int role) const {
    if (!index.isValid() || index.row() < 0 || index.row() >= m_items.size())
        return QVariant();

    const Item &item = m_items[index.row()];

    switch (role) {
    case IsTrainRole:
        return item.isTrain;
    case IdRole:
        return item.id;
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> PCcoreModel::roleNames() const {
    QHash<int, QByteArray> roles;
    roles[IsTrainRole] = "isTrain";
    roles[IdRole] = "id";
    return roles;
}

void PCcoreModel::confirmItem(bool isConfirmed) {
    qInfo() << "PCcoreModel::confirmItem :" << isConfirmed
            << "m_currentIndex :" << m_currentIndex;
    if ((m_currentIndex < 0 || m_currentIndex >= m_items.size()) && m_currentIndex!= -1) {
        qDebug() << "Invalid index:" << m_currentIndex;
        return;
    }
    if(m_currentIndex != -1)
    {
        // 如果确认不通过，移除该项
        if (!isConfirmed) {
            beginRemoveRows(QModelIndex(), m_currentIndex, m_currentIndex);
            m_items.removeAt(m_currentIndex);
            endRemoveRows();
            m_currentIndex--;
        }
    }
    // 处理下一个未训练项
    int i ;
    for (i = m_currentIndex + 1; i < m_items.size(); ++i) {
        if (!m_items[i].isTrain) {
            qInfo() << "image2qml popEye:" << i ;
            qInfo() << "m_items[i].mat : " << m_items[i].mat.cols
                    << "x" <<  m_items[i].mat.rows;
            ImageProvider::getInstance().image2qml(m_items[i].mat, "popEye");
            break;
        }
    }
    m_currentIndex = i;

    // 如果已经处理所有项，发出确认完成信号
    if (m_currentIndex >=  m_items.size()) {
        qInfo() << "finish CcoreModel::confirmItem :";
        m_currentIndex = -1;
        int newId = 0;
        for (auto &item : m_items) {
            item.id = newId++;
        }
        emit confirmationComplete();
    }
}
